<template>
  <div class="contract_company">
    <div class="merak-card merak-container-has-search" v-if="!isQuickAdd"  v-waterMarker="{ zIndex: 10 }" curPageName="665rrrrrrr43f567ab">
      <searchBar
        ref="searchbar"
        searchName="contract_company_cn_ru"
        close-plan 
        :placeholder="$t('contract.enter_placeholder')"
        close-advanced
        @search-event="searchBarPost"
        v-model="searchform"
      >

        <template #footer> 
          <el-button v-auth="{'authArr':auth?.contractCompany??{},'key':'edit'}" type="primary" @click="creatNewCompany(companyFormRef)">{{ $t("contract_company.add_company") }}</el-button>
        </template>
        <!-- 高级搜索弹出框 插槽-->
        <template #searchForm>
          <!--  高级搜索弹出框内容-->
          <div class="modal-content">
            <div class="modal-title"></div>

            <div class="modal—body">
              <el-scrollbar height="100%">
                <div class="scrollbar-content">
                  <!-- 已选参数 组件-->
                </div>
              </el-scrollbar>
            </div>
            <div class="modal-footer">
              <el-button type="default" @click="closeModal">取消</el-button>
              <el-button type="primary" @click="submitForm(ruleFormRef)">搜索</el-button>
              <el-button type="success" @click="showPlanModal">保存搜索方案</el-button>
            </div>
          </div>
          <!--  高级搜索弹出框内容-->
        </template>
        <!-- /高级搜索弹出框 插槽-->
      </searchBar>

      <!-- 表格组件 -->
      <MerakXTable
        v-if="!isQuickAdd"
        ref="tableRef"
        v-bind="tablePayload"
        :handler-click="handleHanderClick"
        :query-columns="queryColumns"
        :query-data="queryData"
        :show-header="true" 
        style="margin-top: 28px"
      >
        <template #handler="{ row }">
          <div style="display: flex" class="action-td">
            <el-button link type="primary" v-auth="{'authArr':auth?.contractCompany??{},'key':'edit'}" @click="editCompany(row)">{{ $t("merak.edit") }}</el-button>
            <el-button v-auth="{'authArr':auth?.contractCompany??{},'key':'delete'}"
              link
              :type="row.delete_disabled == 1 ? '' : 'danger'"
              :disabled="row.delete_disabled == 1"
              @click="detaleCompany(row)"
              >{{ $t("merak.delete") }}</el-button
            >
          </div>
        </template>
      </MerakXTable>
    </div>
    <el-dialog
      modal-class="merak_modal"
      v-model="companyFormDrawer"
      direction="rtl"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      width="500"
    >
      <template #header>
        <div class="merak_modal_title">{{ companyFormTitle }}</div>
      </template>
      <div class="">
        <el-form :model="companyForm" ref="companyFormRef" :rules="companyFormRules" label-position="top">
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item :label="$t('contract_company.contract_company_cn')" prop="contract_company_cn">
                <el-input class="qf_input" v-model="companyForm.contract_company_cn" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item :label="$t('contract_company.contract_company_ru')" prop="contract_company_ru">
                <el-input class="qf_input" v-model="companyForm.contract_company_ru" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <template #footer>
        <el-button type="default" @click="companyCancelEmpty(companyFormRef)">取消</el-button>
        <el-button
          type="primary"
          plain
          :loading="loadingStatus.saveButtonLoading"
          v-if="saveContinueBtnShow"
          @click="saveCompanyContinue(companyFormRef)"
          >保存并继续录入</el-button
        >
        <el-button type="primary" :loading="loadingStatus.saveButtonLoading" @click="saveCompany(companyFormRef)">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="contractCompany">
import router from "@/routers";
import { ref, reactive, computed, watch, onMounted, getCurrentInstance, nextTick } from "vue";

import { ElMessage } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";
import searchBar from "@/components/SearchBar";
import merakColapse from "@/components/merakColapse/index.vue";
import selectedParams from "@/components/SearchBar/components/selectedParams.vue";
import MerakStatCard, { MerakStatCardInstance, MerakStatDataType } from "@/components/MerakStatCard";
import MerakXTable, { MerakXTableInstance, MerakXTableProps } from "@/components/MerakXTable";
import { moreConfirm } from "@/utils/messageUtils";
import useLoading from "@/hooks/useLoading";
import { companyFormInterFace, formRulesInterFace, loadingStatusInerFace } from "./index";
const tableRef = ref<MerakXTableInstance>();

import { ResultEnum } from "@/enums/httpEnum";
import {
  Path,
  contractCompanyField,
  contractCompanyList,
  contractCompanySave,
  contractCompanyDetele,
  getSearchOptions,
  authList
} from "@/api/modules/personalManagementApi/contract";
//import { renewal } from "./index.ts";
 
const { proxy } = getCurrentInstance();

const props = defineProps({
  isQuickAdd: {
    type: Boolean,
    default: false
  },
  showAddForm: {
    type: Boolean,
    default: false
  }
});
const auth=reactive(authList)
const $emit = defineEmits(["companyChangeEvent"]);

//合同即将到期人数
const expirationReminder = ref(0);

// 使用队列 loading 管理初始化页面加载状态
const { queueLoading, queueId } = useLoading();

// 页面配置数据
const columnTypeNew = computed(() => (state.columnType))
const state = reactive<{
  filterOptions: Array<any>;
  statValue: string;
  statData: MerakStatDataType[][];
  statParams: Record<string, string>;
    columnType:Array<any>
}>({
  // 高级搜索方案下拉选项
  filterOptions: [],
  // 统计筛选激活项
  statValue: "",
  // 统计筛选数据
  statData: [],
  // 统计筛选激活后筛选数据
  statParams: {},
  columnType:[]
});

// 动态计算表格的外部筛选数据
const params = computed(() => ({ ...state.statParams }));
console.log(authList?.contractCompany?.export?.show)
// 表格配置属性 
const tablePayload = reactive<MerakXTableProps>({
  // 列设置存储的数据对照值
  columnsByStore: [],
  // 表格行数据的唯一 key, 跟后端同步
  rowKey: "user_id",
  enabledExport:false,//导出
  // 初始化的外部筛选数据
  params,
  // 展示选中列及操作列, 可通过传入对象形式扩展特殊列的渲染插槽, 例如
  columnType: columnTypeNew,
  // 展示选中列及操作列, 可通过传入对象形式扩展特殊列的渲染插槽, 例如
  // ["multiple", { type: 'handle', width: 200, slot: 'custom_slot_name' | ({ row })=> Component }]
  // columnType: ["multiple", "handle"],
  // // 批量操作选项
  // batches: [{ type: "delete", text: "批量删除", color: "red" }],
  // // 操作列选项
  // handles: [{ type: "delete", text: "删除", color: "red" }]
});
 
// 统计筛选激活触发 table 数据请求
const handleStatChange: MerakStatCardInstance["onChange"] = params => {
  state.statParams = params;
};

/**
 * 表格批量操作事件触发
 * @param type 同 tablePayload.batched 子项的 type
 * @param mode 表格选中的模式  current: 当前页  all: 所有页
 * @param selectedKeys 表格当前页选中模式下选中的行数据 key 的集合, 表格所有页选中模式下未选中的行数据 key 的集合
 */
const handleBatchClick: MerakXTableInstance["batchClick"] = async ({ type, mode, selectedKeys }) => {
  switch (type) {
    case "delete":
      return {
        // 是否刷新表格, 默认 false, 可选参数
        refresh: false,
        // 是否重置表格(分页、排序), 默认 false, 可选参数
        reset: true
      };
    default:
      return;
  }
};

/**
 * 表格操作列事件触发
 * @param type 同 tablePayload.handles 子项的 type
 * @param params 表格操作数据, 可结构关于操作行的数据 { row, rowIndex, rowId }
 */
const handleHanderClick: MerakXTableInstance["handlerClick"] = async ({ type, params }) => {
  switch (type) {
    case "delete":
      alert("delete");
      // 是否刷新表格, 默认 false, 可选参数
      return true;
    case "caht":
      alert("caht");
      // 是否刷新表格, 默认 false, 可选参数
      return true;
    default:
      return;
  }
};

// 获取高级搜索方案
const queryFilterOptions = async data => {
  searchbar.value.getPlanList(data.table_id);
  // 初始化接口需要传入队列 loading 暴露的 id
};

// 获取统计数据
const queryStatData = async () => {
  // 初始化接口需要传入队列 loading 暴露的 id
  return getStatistics(queueId.value).then(({ code, data }) => {
    if (code == ResultEnum.SUCCESS) {
      state.statData = Object.values(data).map(item => item);
      if (!!state.statData?.[0]?.[0]) {
        state.statData[0][0].horizontal = true;
      }
    }
  });
};

// 获取表头数据
const queryColumns: MerakXTableInstance["queryColumns"] = async () => {
  // 初始化接口需要传入队列 loading 暴露的 id
  return contractCompanyField(Path.personnel, queueId.value).then(({ code, data }) => {
    if (code == ResultEnum.SUCCESS) {
      //获取表头后使用tableid 获取搜索方案
      queryFilterOptions(data);
      // 克隆表头数据作为列设置的对照数据
      tablePayload.columnsByStore = JSON.parse(JSON.stringify(data.columns));
      return {
        ...data,
        columns: [...data.columns].map(column => {
          switch (column.field) {
            // 扩展插槽悬浮员工姓名展开员工详情卡片
            case "employee_name":
              // 设置最小宽度
              column.width = 180;
              // 固定列
              column.fixed = "left";
                  // 扩展插槽悬浮员工姓名展开员工详情卡片
              column.slots = { default: "employee_details" };
              return column;
            default:
              return column;
          }
        })
      };
    }
  });
};

/**
 * 获取表格数据
 * @param page 分页参数
 * @param sorts 多重排序参数
 * @param filters 表头筛选参数
 * @param from 外部由 tablePayload.params 传入的自定义参数
 */
const queryData: MerakXTableInstance["queryData"] = async ({ page, sorts, from }) => {
  // 创建请求表格数据的参数
  const params: Record<string, any> = {};
  // 如果有分页数据
  if (!!page) {
    Object.assign(params, { ...page });
  }
  // 如果有排序数据
  if (!!sorts) {
    for (let sort of sorts.values()) {
      //console.log(sort);
    }
  }
  // 如果有自定义参数
  if (!!from) {
    for (let key of Object.keys(from)) {
      const item = from[key];
      !!item && (params[key] = item);
    }
  }

  // 初始化接口需要传入队列 loading 暴露的 id
  return contractCompanyList(params, queueId.value).then(({ code, data }) => {

				if (auth?.contractCompany?.delete.show || auth?.contractCompany?.edit.show) { 
					state.columnType = [{ type: 'handle', width: proxy.$t("lang") == 'zh' ? 100 : 200, slot: 'handler' }]
				}

    if (code == ResultEnum.SUCCESS) {
      //console.log(data);
      expirationReminder.value = Number(data.dueContract) || 0;
      return data.table_data;
    }
  });
};

// 初始化页面
const init = async () => {
  //   queryFilterOptions();
  // queryStatData();
  initSearch()
};

// 高级搜索表单
const ruleFormRef = ref<FormInstance>();
const searchform = ref({
  org_company: {
    label: "公司",
    value: "",
    type: "select",
    options: [
      { label: "北京企发", value: 1 },
      { label: "米格速达", value: 2 },
      { label: "新世纪农业", value: 3 }
    ]
  },
  org_department: {
    label: "部门",
    value: "",
    type: "select",
    options: [
      { label: "物流", value: 1 },
      { label: "研发", value: 2 },
      { label: "销售", value: 3 }
    ]
  },
  job_nature: {
    label: "工作性质",
    value: "",
    type: "select",
    options: [
      { label: "全职", value: 1 },
      { label: "兼职", value: 2 }
    ]
  },
  status: {
    label: "状态",
    value: "",
    type: "select",
    options: [
      { label: "在职", value: 1 },
      { label: "试用期", value: 2 }
    ]
  }
});

//高级搜索模态
const searchbar = ref();

//触发了快速搜索或者搜索方案
const searchBarPost = params => {
  //console.log(params);
  let postParams = { ...params.params, ...{ contract_company_cn_ru: params.contract_company_cn_ru } };
  state.statParams = postParams;
};

//点击取消按钮关闭高级搜索模态框
const closeModal = (): void => {
  searchbar.value.modalHide();
  searchbar.value.clear();
};

//打开搜索方案弹出
const showPlanModal = (): void => {
  searchbar.value.showPlanModal();
};

//搜索表单提交
const submitForm = async (formEl: FormInstance | undefined) => {
  state.statParams = { ...searchbar.value.formParams("value") };
  searchbar.value.clear();
  searchbar.value.modalHide();
};
//初始化搜索联动
const initSearch = () => {
  getSearchOptions({'auth_name':'contractCompany'}).then(res => { 
    tablePayload.enabledExport=authList?.contractCompany?.export?.show??false
  });
};

// 编辑和新建公司弹出框

//loading
const loadingStatus = reactive<loadingStatusInerFace>({
  companyFormContextLoading: false, //上下文loading
  saveButtonLoading: false // 保存按钮loading
  //   continueSaveButtonLoading: false // 保存按钮loading
});

let msgCreateNewCompany = proxy.$t("contract.add_company");
let msgEditCompany = proxy.$t("contract.edit_company");
const companyFormTitle = ref<string>(""); //合同公司表单 title
const companyFormRef = ref<FormInstance>(); //合同公司表单 实例
const companyFormDrawer = ref<Boolean>(false); //添加和编辑合同公司表单显示
const saveContinueBtnShow = ref<Boolean>(false); //控制 合同公司表单 继续录入按钮显示

//表单参数结构
const companyForm = ref<companyFormInterFace>({
  contract_company_id: "",
  user_id: "",
  contract_company_cn: "",
  contract_company_ru: ""
});
//表单验证规则
const companyFormRules = reactive<formRulesInterFace>({
  contract_company_ru: [{ required: true, message: proxy.$t("main.requiredMsg"), trigger: "blur" }],
  contract_company_cn: [{ required: true, message: proxy.$t("main.requiredMsg"), trigger: "blur" }]
});

//点击新增按钮创建新公司
const creatNewCompany = (): void => {
  //清空 表单
  companyForm.value.contract_company_cn = "";
  companyForm.value.contract_company_ru = "";
  companyForm.value.contract_company_id = "";
  companyForm.value.user_id = "";
  companyFormDrawer.value = true;
  saveContinueBtnShow.value = true;
  companyFormTitle.value = msgCreateNewCompany;
};

//点击编辑按钮编辑公司
const editCompany = row => {
  let { contract_company_cn, contract_company_ru, contract_company_id, user_id } = row;
  companyForm.value.contract_company_cn = contract_company_cn;
  companyForm.value.contract_company_ru = contract_company_ru;
  companyForm.value.contract_company_id = contract_company_id;
  companyForm.value.user_id = user_id;
  companyForm.value.contract_company_id = contract_company_id;
  companyFormTitle.value = msgEditCompany;
  companyFormDrawer.value = true;
  saveContinueBtnShow.value = false;
};
//点击删除按钮编辑公司
const detaleCompany = row => {
  let { contract_company_id } = row;
  moreConfirm({
    num: 2, //提示次数
    msg: ["确认删除该合同公司吗？", "请再次确认要删除该合同公司！"],
    callback: val => {
      //console.log(val);
      if (val == "confirm") {
        deleteCompany(contract_company_id);
      }
    }
  });
};
//保存继续添加
const saveCompanyContinue = (formEl: FormInstance | undefined) => {
  companySubmit(formEl, true);
};
//保存
const saveCompany = (formEl: FormInstance | undefined) => {
  companySubmit(formEl, false);
};
//取消 关闭模态框清空表单
const companyCancelEmpty = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
  companyFormDrawer.value = false;
};
//保存、编辑 提交信息，
const companySubmit = (formEl: FormInstance | undefined, continueStatus) => {
  if (!formEl) return;
  formEl.validate(vaild => {
    if (vaild) {
      showLoading("saveButtonLoading");
      contractCompanySave({ ...companyForm.value }).then(res => {
        if (res.code === ResultEnum.SUCCESS) {
          ElMessage({
            message: "合同公司保存成功",
            type: "success"
          });

          tableRef?.value?.reloadTable();
          setTimeout(() => {
            continueStatus ? null : (companyFormDrawer.value = false);
            formEl?.resetFields();
            $emit("companyChangeEvent");
            hideLoading();
          }, 1000);
        } else {
          ElMessage({
            message: res.message,
            type: "error"
          });
          hideLoading();
        }
      });
    } else {
    }
  });
};
//删除公司，
const deleteCompany = contract_company_id => {
  contractCompanyDetele({ contract_company_id }).then(res => {
    if (res.code === ResultEnum.SUCCESS) {
      ElMessage({
        message: "合同公司删除成功",
        type: "success"
      });
      tableRef?.value.reloadTable();
    } else {
      ElMessage({
        message: res.message,
        type: "error"
      });
    }
  });
};

//loading 显示控制
const showLoading = name => {
  loadingStatus[name] = true;
};
const hideLoading = () => {
  loadingStatus.saveButtonLoading = false;
};

// 监听初始化队列 loading 状态
watch(queueLoading, () => {
  if (queueLoading.value) {
    // 页面初始化队列 loading 时不允许 table 自动 loading
    tablePayload.loading = false;
  } else if ("loading" in tablePayload) {
    // 队列 loading 完成后清除 table 受控的 loading 属性
    delete tablePayload.loading;
  }
});
// watch(
//   () => props.showAddForm,
//   val => {

//     if (val) {
//       creatNewCompany();
//     }
//   }
// );

// 运行初始化
onMounted(() => {
  init();
});

defineExpose({
  show: creatNewCompany
});
</script>

<style scoped lang="scss">
@import "./index.scss";
</style>